/**
 * @author zhangqiang
 * @date   17/7/20
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import { Toast,Checkbox,Modal} from 'antd-mobile'
import { bindActionCreators } from 'redux'
import { getHandleList} from '../../actions/handleListActions';
//通用组件
import {FootNav} from '../../components/common'
import CheckAndArrow from '../../components/handleList'
import {subMitForm} from  '../../actions/homeActions'
import common from '../../utils/common'
import {deleteHandle} from '../../actions/handleListActions'
import '../../../styles/handleList.scss';
import style from './index.scss'
const alert = Modal.alert;

class HandleList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			carNum: '',
			carId: '',
			days: this.props.days, // 年检剩余时间
			states: -1,
			violaNum: 0, //
			checkALL: false, // 是否全选
			passiveCheckAll: false, // 这个记录单个勾选，造成全选按钮的变化
			data: [],
			copyData: [], // 这里是为了备份
			inspectionType: 0,//
			name: '',
			phone: '',
			dataLEN: -1,   //判断是否全部没有选中
			checkList: [], //勾选的数据
			handleList:[]  //立即办理列表
		}
	}

	toUrl(url) {
		this.context.router.push(url);
	}

	componentDidMount() {
		common.setViewTitle('港澳通行证签注办理');
		sessionStorage.setItem('getRegionType',1)
		this.getHandleList()
	}

	getHandleList(){
		let getData={}
		this.props.dispatch(getHandleList(getData,(data)=>{
			for(let i=0;i<data.length;i++){
				data[i].check=true
				data[i].key=i
				data[i]['endorseInfoObj'] = data[i].orderEndorsement
				delete data[i]['orderEndorsement']
			}

			let checkALL = this.state.checkALL;
			let dataViolaNum = 0;
			for (var i = 0, dataLEN = 0; i < data.length; i++) {
				if (data[i].check) dataLEN++
			}
			checkALL = dataLEN == data.length ? true : false;
			if(!data.length){  //当删除完订单列表，就直接跳到填写资料页
				this.toUrl('home')
			}else {
				this.setState({
					data: data,
					checkALL: checkALL,
				});
			}
		}));
	}

	//返回（CheckAndArrow组件返回的数据） 表单里面选择的情况：勾选/右侧进入详情
	// 单个勾选效果,传入勾选的KEY和VALUE；
	changeONECheckData(type, key, check) {
		let replaceData = { key: parseInt(key), check: check };
		let checkALL = this.state.checkALL;
		let data = this.state.data; // 默认数据

		// 遍历是否是全选:check=true

		for (var i = 0, dataLEN = 0; i < data.length; i++) {
			if (i == replaceData.key) {
				 data[replaceData.key].check = replaceData.check ? false : true;
			}
			if (data[i].check) dataLEN++
		}
		checkALL = dataLEN == data.length ? true : false;
		this.setState({
			dataLEN: dataLEN,
			checkALL: checkALL,
			data: data,
		});
		let arr=[];
		for(let i=0;i<data.length;i++){
			if(data[i].check){
				arr.push(data[i])
			}
		}
		this.setState({
			checkList: arr
		})
	}

	isAgreeState(){
		this.setState({
			isAgree: !this.state.isAgree
		});
	}

	deleteHand(event,name,id){
		alert('', '确定取消('+name+'，'+id+')通行证业务办理？', [
			{ text: '取消', onPress: () => console.log('cancel') },
			{
				text: '确定',
				onPress: () => {
					let postData={
						passCode: id
					}
					this.props.dispatch(deleteHandle(postData,(res=>{
						this.getHandleList()
					})))
				}
			},
		])
		event.stopPropagation();
	}

	toAddPass(){
		sessionStorage.removeItem('cacheAllState')
		this.toUrl('home')
	}

	subMit(type){
		let checkArr=[], //选择的数据
			wholeArr=[]; //未做选择的数据
		for(let i=0;i<this.state.checkList.length;i++){
			let obJect1={
				"endorseInfoObj": JSON.stringify(this.state.checkList[i].endorseInfoObj),
				"address": JSON.stringify(this.state.checkList[i].endorseInfoObj.address),
				"key": 0,
				"items": JSON.stringify(this.state.checkList[i].endorseInfoObj.items)
			}
			checkArr.push(obJect1)
		}

		for(let i=0;i<this.state.data.length;i++){
			let obJect2={
				"endorseInfoObj": JSON.stringify(this.state.data[i].endorseInfoObj),
				"address": JSON.stringify(this.state.data[i].endorseInfoObj.address),
				"key": 1,
				"items": JSON.stringify(this.state.data[i].endorseInfoObj.items)
			}
			wholeArr.push(obJect2)
		}

		if(this.state.dataLEN==0&&type!='toHome'){
			Toast.info('请选择需要办理的通行证',1)
			return
		}
		let data1 = {
			endorseInfoList: checkArr
		};
		let data2 = {
			endorseInfoList: wholeArr
		};

		let postData1 = {
			objStr: checkArr.length >0 ?JSON.stringify(data1):JSON.stringify(data2)
		}

		sessionStorage.setItem('pay_data',postData1.objStr);

		if(type=='toHome'){
			sessionStorage.setItem('handeListGetIntId',1)
			sessionStorage.removeItem('currentIndex')   //删除请求地区种类的序号，防止用户从缓存进入填写资料页，切换签注类别，再次点击返回，

			sessionStorage.removeItem('cacheAllState')
			setTimeout(()=>{this.toUrl('home')},100)
		}else {
			if(JSON.parse(postData1.objStr).endorseInfoList.length>5){
				Toast.info('一个订单不能超过5个证件同时办理！',1)
				return;
			}
			this.props.dispatch(subMitForm(postData1,(res)=>{
				sessionStorage.setItem('checkout_success_data',JSON.stringify(res)); //支付页面的数据
				setTimeout(()=>{this.toUrl('payment')},100)
			}))
		}

	}

	render() {

		return (
			<div className={style.handleList}>
				<div className={style.handleCheck}>
						<CheckAndArrow className={style.borderT} data={this.state.data}
							onClick={(type, key, value) => this.changeONECheckData(type, key, value)}
							onDeleteHand={(event,name,id)=>{this.deleteHand(event,name,id)}}
						/>
				</div>

				<div style={{height: '.28rem'}}></div>
				{/*
				<div className={style.agreeBox}>
		        <span onClick={()=>{this.isAgreeState()}}>
			        <img className={style.agree} src={this.state.isAgree?'./images/agree.png':'./images/noCheck.png'} alt=""/>
			        <span className={style.determine}>同意</span>
		        </span>
					<span className={style.agreeBtn}>《港澳通行证办理协议》</span>
				</div>
				*/}
				<div style={{height: '.42rem'}}></div>
				<div className={style.btnBox}>
					<button className={style.handle} type='button' onClick={()=>{this.subMit()}}>立即办理</button>
					<button className={style.preservation} type='button' onClick={()=>{this.subMit('toHome')}
					}><img src="./images/group.png" alt=""/>办理下一个通行证</button>
				</div>

				{/*底部导航菜单 start*/}
				<FootNav data={{footNavType:'hk'}}/>
				{/*底部导航菜单 end*/}
			</div>
				)
    }
}

//使用context
HandleList.contextTypes = {
    router: React.PropTypes.object.isRequired
};

HandleList.defaultProps = {
	handleList:[],
	modalTLT: '请确认上述所有项目已完成',
	days: '?',
};

function mapStateToProps(state) {
	return Object.assign({}, state.passHandleList);
}

export default connect(mapStateToProps)(HandleList);
